// API 请求工具函数
const api = {
    async request(url, options = {}) {
        try {
            const response = await fetch(url, {
                headers: {
                    'Content-Type': 'application/json',
                    ...options.headers
                },
                ...options
            });

            const data = await response.json();

            if (!response.ok) {
                throw new Error(data.error || '请求失败');
            }

            return data;
        } catch (error) {
            throw error;
        }
    },

    async post(url, data) {
        return this.request(url, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    },

    async get(url) {
        return this.request(url);
    },

    async put(url, data) {
        return this.request(url, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
    },

    async delete(url) {
        return this.request(url, {
            method: 'DELETE'
        });
    }
};

// 用户认证管理
class AuthManager {
    constructor() {
        this.currentUser = null;
        this.checkAuthStatus();
    }

    // 检查认证状态
    async checkAuthStatus() {
        try {
            const userData = await api.get('/api/user');
            this.currentUser = userData;
            return true;
        } catch (error) {
            this.currentUser = null;
            return false;
        }
    }

    // 注册
    async register(username, password, confirmPassword) {
        try {
            const result = await api.post('/api/register', {
                username,
                password,
                confirmPassword
            });
            return { success: true, message: result.message };
        } catch (error) {
            return { success: false, message: error.message };
        }
    }

    // 登录
    async login(username, password) {
        try {
            const result = await api.post('/api/login', {
                username,
                password
            });
            this.currentUser = result.user;
            return { success: true, message: result.message };
        } catch (error) {
            return { success: false, message: error.message };
        }
    }

    // 退出登录
    async logout() {
        try {
            await api.post('/api/logout');
            this.currentUser = null;
            return { success: true };
        } catch (error) {
            return { success: false, message: error.message };
        }
    }

    // 检查是否已登录
    isLoggedIn() {
        return this.currentUser !== null;
    }

    // 获取当前用户
    getCurrentUser() {
        return this.currentUser;
    }

    // 检查是否为管理员
    isAdmin() {
        return this.currentUser && this.currentUser.role === 'admin';
    }

    // 保存游戏数据
    async saveGameData(gameName, data) {
        try {
            await api.post(`/api/game-data/${gameName}`, { data });
            return { success: true };
        } catch (error) {
            return { success: false, message: error.message };
        }
    }

    // 加载游戏数据
    async loadGameData(gameName) {
        try {
            const data = await api.get(`/api/game-data/${gameName}`);
            return data;
        } catch (error) {
            return {};
        }
    }
}

// 消息提示工具
const showMessage = (message, type = 'info') => {
    const messageEl = document.getElementById('message');
    messageEl.textContent = message;
    messageEl.className = `message ${type}`;
    messageEl.classList.add('show');

    setTimeout(() => {
        messageEl.classList.remove('show');
    }, 3000);
};

// 创建全局认证管理器实例
const authManager = new AuthManager();